package com.justech.eat.service.impl;

import com.justech.eat.mapper.mysql.LocationAccMonitorLogMapper;
import com.justech.eat.mapper.sqlserver.AccMonitorLogMapper;
import com.justech.eat.entity.AccMonitorLog;
import com.justech.eat.repository.AccMonitorLogRepository;
import com.justech.eat.service.DiningRecordSupplier;
import com.justech.eat.service.UserService;
import com.justech.eat.service.component.ProcessingJobNoAccMonitorLogParser;
import com.justech.eat.service.component.impl.ProcessingJobNoAccMonitorLogParserImpl;
import com.justech.eat.util.LocationDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: eat-service
 * @description:
 * @author: feifei.li
 * @create: 2020-05-25 14:01
 **/
@Service
public class DiningRecordSupplierImpl implements DiningRecordSupplier {
    @Autowired
    AccMonitorLogMapper accMonitorLogMapper;

    @Autowired
    LocationAccMonitorLogMapper locationAccMonitorLogMapper;

    @Autowired
    UserService userService;

    @Autowired
    AccMonitorLogRepository accMonitorLogRepository;

    /**
     * 同步数据
     * 每次同步数据都会覆盖之前的记录
     *
     * @param date
     */
    @Override
    public void synchronization(String date) {
        locationAccMonitorLogMapper.empty();
        List<AccMonitorLog> accMonitorLogMapperByDate = accMonitorLogMapper.findByDate(date, LocationDateUtil.tomorrow());

        ProcessingJobNoAccMonitorLogParser accMonitorLogParser = new ProcessingJobNoAccMonitorLogParserImpl(date);
        accMonitorLogParser.setSysUsers(userService.getAll());

        List<AccMonitorLog> parsedAccMonitorLogs = accMonitorLogParser.parse(accMonitorLogMapperByDate);
        accMonitorLogRepository.saveAll(parsedAccMonitorLogs);
    }

    /**
     * 查询某天的订餐记录
     *
     * @param date 如果取不到数据，则选择再次同步数据
     * @return
     */
    @Override
    public List<AccMonitorLog> getDiningRecords(String date) {
        if (locationAccMonitorLogMapper.count() == 0) {
            synchronization(date);
        }
        return locationAccMonitorLogMapper.findAll();
    }


    /**
     * 获取所有用户用餐信息
     *
     * @param date
     * @return key：用户工号和就餐类别; value：就餐信息
     */
    @Override
    public Map<String, AccMonitorLog> getAccMonitorMap(String date) {
        List<AccMonitorLog> diningRecords = getDiningRecords(date);
        HashMap<String, AccMonitorLog> stringAccMonitorLogHashMap = new HashMap<>();
        for (AccMonitorLog diningRecord : diningRecords) {
            stringAccMonitorLogHashMap.put(diningRecord.getJobNumber() + "_" + diningRecord.getType(), diningRecord);
        }
        return stringAccMonitorLogHashMap;
    }
}
